// 文件相关接口
import {resp} from '@srcUtils/resp';
import {Request, Response} from 'express';
import {Handler} from '@/types/route';
import {FileUtils} from '@srcUtils/utils';

const multiparty = require('multiparty');
const fs = require('fs');
const StaticPath = './src/static';

// 接收上传的文件，大小限制20mb
export const upload: Handler = async (req: Request, res: Response) => {
    const form = new multiparty.Form();
    form.encoding = 'utf-8';
    const tempPath = StaticPath;
    form.uploadDir = tempPath;
    // 先同步创建目录
    const existRes = await FileUtils.existFolder(tempPath);
    console.log(existRes);
    // code 不为 0，表示失败
    if (existRes.code === 0) {
        // 临时文件存储
        form.parse(req, (err, fields, files) => {
            console.log(err);
            try {
                console.log(files, '-----', fields);
                const inputFiles = fields.file;
                for (const inputFile of inputFiles) {
                    const uploadedPath = inputFile.path;
                    const newPath = form.uploadDir + '/' + inputFile.originalFilename;
                    console.log(newPath);
                    fs.renameSync(uploadedPath, newPath);
                }
                res.json(resp.setSuccess().collect());
            } catch (err) {
                console.log(err);
                res.json(resp.setCode(500).setMsg('internal error').collect());
            }
        });
        return;
    }
    res.json(resp.setFail().setMsg('internal error').collect());
};

export const downloadFile: Handler = (req: Request, res: Response) => {
    const filename = '工作簿1.xlsx';
    const userAgent = (req.headers['user-agent'] || '').toLowerCase();
    res.setHeader('Content-Type', 'application/octet-stream;charset=UTF8');
    if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('chrome') >= 0) {
        res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename));
    } else if (userAgent.indexOf('firefox') >= 0) {
        res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(filename) + '"');
    } else {
        res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(filename).toString('binary'));
    }
    res.download(StaticPath + filename, filename, (err: Error) => {
        if (err) {
            res.json(resp.setFail().setMsg('file not existed').collect());
        }
    });
};
